package com.yh.travel.upload.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @ClassName FileDfsUtil
 * @Description 上传文件工具类
 * @Author 0715-YuHao
 * @Date 2020/11/2 10:16
 * @Version 1.0
 */
@Component
public class FileDfsUtil {
    @Resource
    private FastFileStorageClient storageClient ;

    /**
     * @Author 0715-YuHao
     * @Description 上传文件
     * @Date 10:18 2020/11/2
     * @Param [multipartFile]
     * @return java.lang.String
     **/
    public String upload(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename , null);
        return storePath.getFullPath() ;
    }

    /**
     * @Author 0715-YuHao
     * @Description 删除文件
     * @Date 10:18 2020/11/2
     * @Param [fileUrl]
     * @return void
     **/
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            throw new RuntimeException("fileUrl == >>文件路径为空...");
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
